package com.huilian.tool.common.utils;

import com.huilian.tool.common.config.WorkWeiXinConfig;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 企业微信工具类
 * @Author 少凡
 * @Date 2022-06-24 14:03
 * version 1.0
 */
@Slf4j
public class WorkWeiXinUtil {

    /**
     * 验证URL是否可用
     * @param request
     * @return
     * @throws AesException
     */
    public static String verifyUrl(HttpServletRequest request,WorkWeiXinConfig workWeiXinConfig) throws AesException {
        String msg_signature = request.getParameter("msg_signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        Enumeration pNames=request.getParameterNames();
        while(pNames.hasMoreElements()){
            String name=(String)pNames.nextElement();
            String value=request.getParameter(name);
            System.out.println(name + "=" + value);
        }

        WXBizMsgCrypt wxBizJsonMsgCrypt = new WXBizMsgCrypt(workWeiXinConfig.getToken(), workWeiXinConfig.getEncodingAESKey(), workWeiXinConfig.getCorpid());
        return wxBizJsonMsgCrypt.VerifyURLWorkWeiXin(msg_signature, timestamp, nonce, echostr);
    }


    /**
     * @param request
     * @param appId 指令验证，APPID传入第三方应用的APPID即SUITE_ID  数据验证，APPID传入的是授权企业的AUTH_CORPID
     * @return
     * @throws AesException
     * @throws DocumentException
     */
    public static Map<String, String> getMapDate(HttpServletRequest request, WorkWeiXinConfig workWeiXinConfig,String appId) throws AesException, DocumentException, IOException {
        String msg_signature = request.getParameter("msg_signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String encryptMsg = streamToString(request);
        log.info("msg_signature：{}",msg_signature);
        log.info("timestamp：{}",timestamp);
        log.info("nonce：{}",nonce);
        log.info("encryptMsg：{}",encryptMsg);
        log.info("workWeiXinConfig.getToken()：{}",workWeiXinConfig.getToken());
        log.info("workWeiXinConfig.getEncodingAESKey()：{}",workWeiXinConfig.getEncodingAESKey());
        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(workWeiXinConfig.getToken(), workWeiXinConfig.getEncodingAESKey(), appId);
        String result = wxBizMsgCrypt.DecryptMsgWorkWeiXin(msg_signature, timestamp, nonce, encryptMsg);
        Map<String, String> map = new HashMap<>();
        //将解密后的消息转为xml
        Document doc = DocumentHelper.parseText(result);
        Element root = doc.getRootElement();
        List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        return map;
    }

    /**
     * 输入流转字符串
     * @param request
     * @return
     * @throws IOException
     */
    public static String streamToString(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();

    }

    public static long formatTime(String time){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(sdf.parse(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  calendar.getTimeInMillis() / 1000L;
    }


}
